package com.jgzx.utils;

import cn.hutool.core.bean.BeanUtil;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * bean对象与map互转
 */
public class BeanToMapUtil {

    /**
     * bean对象转map
     * @param obj
     * @return
     */
    public static Map<String, String> beanToMap(Object obj){
        if(obj == null){
            return null;
        }
        Map<String, String> map = new HashMap<>();
        try {
            Field[] declaredFields = obj.getClass().getDeclaredFields();
            for (Field field : declaredFields) {
                field.setAccessible(true);
                map.put(field.getName(), field.get(obj)==null ? "" : String.valueOf(field.get(obj)));
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return map;
    }

    /**
     * map转bean对象
     * @param map
     * @param beanClass
     * @return
     * @throws Exception
     */
    public static <T> T mapToBean(Map<String, String> map, Class<T> beanClass){
        return BeanUtil.mapToBean(map, beanClass, true);
    }
}
